package ase.eleitweg.server;

import ase.eleitweg.common.*;
import ase.eleitweg.server.db.*;

import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;
import java.util.Vector;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.dao.support.DaoSupport;
import org.apache.log4j.*;

import com.google.inject.Inject;


public class UserController implements UserManager {
	
	private static Logger log = Logger.getLogger(UserController.class);

	//private ELeitwegDAO dao;

	/**
	 * Initiate the DB-Interface
	 */
	/*private void initDAO() {
		dao = DatabaseFactory.getDB();

	}*/
	
	@Inject ELeitwegDAO dao;
	private UserController() {
		//initDAO();
	}
	
	private static UserController instance = null;
	
	private static UserManager remoteInstance = null;
	
	public static UserController getInstance() {
		if(instance==null) {
			instance = new UserController();
		}
		return instance;
	}
	
	public static UserManager getRemoteInstance() throws RemoteException {
		if(instance == null) {
			instance = new UserController();
		}
		if(remoteInstance == null) {
			remoteInstance = (UserManager) UnicastRemoteObject.exportObject((UserManager) instance, 0);
		}
		return remoteInstance;
	}
	
	public List<User> getUsers() {
		return dao.getUsers();
	}
	
	public void deleteUser(User u) {
		List<Group> groups = dao.getGroups();
		for(Group g : groups) {
			if(g.isMember(u)) {
				dao.deleteUserGroup(g, u);
			}
		}
		dao.deleteUser(u);
		
	}
	
	public int addUser(User u) {
		for(User ux : dao.getUsers()) {
			if(ux.getUsername().equals(u.getUsername())) {
				return -1;
			}
		}
		return dao.createUser(u);
	}
	
	public void updateUser(User u) {
		dao.updateUser(u);
	}
	
	public List<Group> getGroups() {
		return dao.getGroups();
	}
	
	public void deleteGroup(Group g) {
		dao.deleteGroup(g);
	}

	public int addGroup(Group g) {
		for(Group gx : dao.getGroups()) {
			if(gx.getName().equals(g.getName())) {
				return -1;
			}
		}
		return dao.createGroup(g);
	}
	
	public void updateGroup(Group g) {
		dao.updateGroup(g);
	}
	
	public void addUserToGroup(User u, Group g) {
		dao.addUserToGroup(g, u);
	}
	
	public void removeUserFromGroup(User u, Group g) throws RemoteException {
		dao.deleteUserGroup(g, u);
	}
	
	public User getUserById(int id) {
		return dao.getUserById(id);
	}
	
	public Group getGroupById(int id) {
		return dao.getGroupById(id);
	}
}
